package com.locpx.lct;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

import javax.imageio.ImageIO;

/**
    GameManager manages all parts of the game.
 */
public class LCTManager extends LCTCore {
	static String lctImgFileName = null;
	static String bgImgFileName = null;

    public static void main(String[] args) {
    	final Properties inputprops = new Properties();
        final File inputpropFile = new File(".input");
        
        if (inputpropFile.exists()) {
            try {
                inputprops.load(new FileInputStream(inputpropFile));
                lctImgFileName = inputprops.getProperty("lct_image");
            	bgImgFileName = inputprops.getProperty("background_image");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        new LCTManager().run();
    }

    private Image lctImg;
    private Image bgImg;
    private float yPos;
    private TimeSmoothie timeSmoothie = new TimeSmoothie();
    private Properties props = new Properties();
    private Properties configs = new Properties();
    private InputManager inputManager;

    private GameAction exit;
    private GameAction pause;
    private GameAction speedUp;
    private GameAction speedDown;

    private static final int DEFAULT_SPEED = 60;
    
    private int speed = DEFAULT_SPEED;
    
    private BufferedImage backScreenImage;
    private Graphics2D backScreen;

    public void init() {
        super.init();

        yPos = screen.getHeight();

        inputManager = new InputManager(
                screen.getFullScreenWindow());
        inputManager.setCursor(InputManager.INVISIBLE_CURSOR);

        exit = new GameAction("exit",
                GameAction.DETECT_INITAL_PRESS_ONLY);
        pause = new GameAction("pause",
                GameAction.DETECT_INITAL_PRESS_ONLY);
        speedUp = new GameAction("speedUp",
                GameAction.DETECT_INITAL_PRESS_ONLY);
        speedDown = new GameAction("speedDown",
                GameAction.DETECT_INITAL_PRESS_ONLY);

        inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
        
        inputManager.mapToKey(pause, KeyEvent.VK_P);
        
        inputManager.mapToKey(speedUp, KeyEvent.VK_U);
        inputManager.mapToKey(speedDown, KeyEvent.VK_D);
        
        inputManager.mapToKey(speedUp, KeyEvent.VK_UP);
        inputManager.mapToKey(speedDown, KeyEvent.VK_DOWN);
        
        try {
        	if (lctImgFileName != null && !lctImgFileName.equals("")) {
        		try {
        			lctImg = ImageIO.read(new File(lctImgFileName));
        		} catch (Exception e) {
        			lctImg = ImageIO.read(new File("LCT.png"));
				}
        	} else {
        		lctImg = ImageIO.read(new File("LCT.png"));
        	}
        	
        	if (bgImgFileName != null && !bgImgFileName.equals("")) {
        		try {
        			bgImg = ImageIO.read(new File(bgImgFileName));
        		} catch (Exception e) {
        			bgImg = ImageIO.read(new File("bg.png"));
				}
        	} else {
        		bgImg = ImageIO.read(new File("bg.png"));
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        double lctScale = determineImageScale(lctImg.getWidth(null), lctImg.getHeight(null), screen.getWidth(), screen.getHeight());
        
        lctImg = lctImg.getScaledInstance((int) (lctImg.getWidth(null) * lctScale), (int) (lctImg.getHeight(null) * lctScale), Image.SCALE_SMOOTH);
        
        double bgScale = determineImageScale(bgImg.getWidth(null), bgImg.getHeight(null), screen.getWidth(), screen.getHeight());
        bgImg = bgImg.getScaledInstance((int) (bgImg.getWidth(null) * bgScale), (int) (bgImg.getHeight(null) * bgScale), Image.SCALE_SMOOTH);
        
        backScreenImage = new BufferedImage(screen.getWidth(), screen.getHeight(), BufferedImage.TYPE_INT_ARGB);
        backScreen = backScreenImage.createGraphics();

        // load resources (in separate thread)
        new Thread() {
            public void run() {
                try {
                    File propFile = new File(".LCT");
                    if (propFile.exists()) {
                        props.load(new FileInputStream(propFile));

                        try {
                            speed = Integer.parseInt(props.getProperty("speed"));
                        } catch (NumberFormatException e) {
                            speed = DEFAULT_SPEED;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                try {
                    File configFile = new File("lct.conf");
                    if (configFile.exists()) {
                        configs.load(new FileInputStream(configFile));
                        try {
                            fps = Integer.parseInt(configs.getProperty("fps"));
                        } catch (NumberFormatException e) {
                            fps = DEFAULT_FPS;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private double determineImageScale(int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) {
        double scalex = (double) targetWidth / sourceWidth;
        double scaley = (double) targetHeight / sourceHeight;
        return Math.max(scalex, scaley);
    }
    
    /**
        Closes any resurces used by the LCTManager.
     */
    public void stop() {
        super.stop();
    }

    public void update(long elapsedTime) {
        elapsedTime = timeSmoothie.getTime(elapsedTime);
        
        if (yPos < -lctImg.getHeight(null)) {
            yPos = screen.getHeight();
        } else {
            yPos -= speed/100f;
        }
    }
    
    public void render() {
        // draw background image
        backScreen.drawImage(bgImg, 0, 0, null);

        // draw lct image
        backScreen.drawImage(lctImg, 0, (int)yPos, null);
    }

    public void draw(Graphics2D g) {
        // draw back screen image
        g.drawImage(backScreenImage, 0, 0, null);
    }
    
    public void checkInput() {

        if (exit.isPressed()) {
            stop();
            
            File propFile = new File(".LCT");
            try {
                props.setProperty("speed", "" + speed);
                props.store(new FileOutputStream(propFile), null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (pause.isPressed()) {
            pause();
        }
        
        if (!isPaused && speedUp.isPressed()) {
            speed++;
        }
        
        if (!isPaused && speedDown.isPressed()) {
            if (speed > 1) {
                speed--;
            }
        }
    }

}
